import { _decorator, Component, Button, Label,Collider2D,Contact2DType,IPhysics2DContact, SpriteAtlas,Sprite, RichText, instantiate, Prefab, v3, Vec3, tween, UITransform,UIOpacity, Node, math } from 'cc';
import { Prg } from './prg';
import { Assassin } from './assassin';
import { Room } from './room';
import { Util } from './util';
import { Http } from './http';
import { User } from './user';
import { Config } from './config';
const { ccclass, property } = _decorator;


const GameStatusWaiting = 0
const GameStatusStart = 1
const GameStatusKilling = 2
const GameStatusSettle = 3

const GameCountdown = 60


@ccclass('main')
export class main extends Component {

    nodeUITransform:UITransform

    roomsAreaWidth:number
    roomsAreaHeight:number

    roomsUITransform:UITransform

    speed = 300
    enterPosition:Vec3

    corner1Position:Vec3
    enterToCorner1Duration:number

    corner2Position:Vec3
    enterToCorner2Duration:number

    selectMoneyButton:Node
    roomCoinNodes: Array<Node> = []

    rooms: Array<Room> = []

    toastNode:Node
    toastMsgLabel:Label
    tipNode:Node
    tipMsgIndex:number = 0


    @property({
        type:Prefab,
        displayName: "其他角色"
    })
    prgOtherPre:Prefab

    @property({
        type:Prefab,
        displayName: "主角"
    })
    prgPre:Prefab

    @property({
        type:Prefab,
        displayName: "金币数量"
    })
    coinNumberPre:Prefab

    @property({
        type:Prefab,
        displayName: "水平门"
    })
    doorHorizontalPre:Prefab

    @property({
        type:Prefab,
        displayName: "垂直门"
    })
    doorVerticalPre:Prefab

    @property({
        type:SpriteAtlas,
        displayName: "数字集"
    })
    numbersSprite:SpriteAtlas

    initAreaStartPostion: Vec3
    initAreaWidth: number
    initAreaHeight: number

    alertWindow: Node
    alertWindowAssassin: Node
    alertWindowSuccess: Node
    alertWindowFailure: Node
    alertWindowBystander: Node
    alertWindowBystanderLabel: Label

    selectedMask: Node
    selectedMaskUITransform:UITransform

    countdownNode: Node
    countdownNumber: Node

    prgOthersMapping:Map<number, Prg> = new Map()

    doorStatus:number = 1 // 0关闭 1打开
    openDoor:(func: () => void) => void
    closeDoor:(func: () => void) => void

    prgNode:Node
    prgBetAreaNode:Node
    prgBetNumberLabel:Label
    prgMyself:Prg = null
    assassinNode: Node
    assassin:Assassin
    enterMainPostion: Vec3
    assassinTargetRoomIndex:number = -1

    status: number = 1

    promptBoxNumber: Node
    promptBoxStartNumber: Node
    promptBox: Node
    promptBoxStageLabel: Label

    gameStatus:number = GameStatusWaiting

    

    enterSign:boolean = false

    coinNumberMy:Node

    accountBalance:number

    survivalId:number = 0

    countdown:number = -1

    userTargetRoomIndex:number = -1
    userBetFee:number = 0
    userWinFee:number = 0
    userId:number = 0
    userAccountBalance:number = 0

    userSelectBetFee:number = 0.1

    roomNameMapping:Map<number, string> = new Map([
        [0, "休息厅"],
        [1, "农家院"],
        [2, "办公室"],
        [3, "小木屋"],
        [4, "杂物间"],
        [5, "餐厅"],
        [6, "卫生间"],
        [7, "音乐厅"],
    ]); 

    areaShow:boolean = false

    lastDeadRoomIndex:number = -1

    token:string = ""
    

    start() {

        this.node.on(Node.EventType.TOUCH_START, function(t) {

            let pos = t.getUILocation()
            this.nodeUITransform = this.node.getComponent(UITransform)
            let worldPos = this.nodeUITransform.convertToNodeSpaceAR(v3(pos.x, pos.y)); 
            //console.log(this.gameStatus)
            if (this.gameStatus == GameStatusKilling) {
                return
            }
            for (let room of this.rooms) {
                if (room.selected(worldPos)) {

                    if (this.userTargetRoomIndex != -1 && this.prgMyself.moving) {
                        return
                    }

                    this.selectedMask.active = true
                    this.selectedMask.setPosition(room.areaPostion)
                    this.selectedMaskUITransform.width = room.areaWidth
                    this.selectedMaskUITransform.height = room.areaHeight
                    let selectedMaskUIOpacity = this.selectedMask.getComponent(UIOpacity)
                    tween(selectedMaskUIOpacity).then(tween().to(1,{opacity:255}).to(1,{opacity:125})).repeatForever().start();
   
                    if (this.userTargetRoomIndex == -1) {
                        this.userTargetRoomIndex = room.id
                    } else if (this.userTargetRoomIndex != -1 && room.id != this.userTargetRoomIndex) {
                        this.userTargetRoomIndex = room.id
                        this.prgMyself.changeTargetRoom(this.rooms[this.userTargetRoomIndex])

                        Http.changeRoom(this.token, this.userSelectBetFee, this.survivalId, this.userTargetRoomIndex + 1).then((response) => {
                        })
                    }

                    break
                }
            }
            
        },this)


        this.init()


        let collider = this.assassin.node.getComponent(Collider2D);
        collider.on(Contact2DType.BEGIN_CONTACT, function(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
            // 只在两个碰撞体开始接触时被调用一次
            if (this.assassin.targetRoom.doorNode.name == otherCollider.node.name) {

                this.assassin.pause()
                this.assassin.targetRoom.open(() => {
                    this.assassin.resume()
                })
            }
            
        }, this);


        let logger = this.node.getChildByName("logger")
        let loggerUITransform = logger.getComponent(UITransform)
        loggerUITransform.priority = 70
        logger.setPosition(v3(logger.getPosition().x, -this.roomsAreaHeight/2 - 50))
        logger.on(Node.EventType.TOUCH_START, function(t) {

            window.location.href = Config.appDomain() + "#/qiliRecord"
            // let index = Util.getRandmNumber(1, 8)
            // Http.joinTest(10, this.survivalId, index)
            
            
        },this)

    
        let func = () => {
            //console.log("countdown="+ this.countdown)
            let countdownFunc = () => {            
                if (this.countdown != -1 && this.countdown >= 0) {
                    if (this.countdown < 0) {
                        this.countdown = -1
                        return
                    }
                    
                    if (this.countdown >= 0) {
                        this.genCoinNumber(20, 40, 0, this.countdownNumber, this.countdown)
                    }

                    if (this.countdown == 0) { 
                        this.gameStatus = GameStatusKilling
                        this.countdownNode.active = false
                        this.showAssassinAlert(() => {
                            
                            this.closeDoor(() => {
                                this.assassin.move(() => {
                                    this.assassin.targetRoom.close(() => {

        
                                        this.prgOthersMapping.forEach((p , key) =>{
                                            if (p.targetRoom != null && p.targetRoom.id == this.assassin.targetRoom.id) {
                                                this.genCoinNumber(21, 42, 3, this.assassin.targetRoom.roomCoinNode, 0)
                                                p.node.destroy()
                                            }
                                            
                                        })

                                        // 清空本地缓存
                                        let clearAllFunc = ()=>{
                                            this.gameStatus = GameStatusWaiting
                                            this.enterSign = false
                                            this.prgOthersMapping = new Map()
                                            User.clear(this.survivalId)
                                            this.survivalId = 0
                                            this.prgMyself = null
                                            this.userTargetRoomIndex = -1
                                            this.assassinTargetRoomIndex = -1
                                            for (let room of this.rooms) {
                                                this.genCoinNumber(21, 42, 3, room.roomCoinNode, 0)
                                            }
                                            this.prgBetAreaNode.active = false
                                            this.prgBetNumberLabel.string = ""
                                            this.selectedMask.active = false
                                        }


                                        if (this.userBetFee == 0) {
                                            this.showBystanderAlert(this.assassin.targetRoom.coinCount, clearAllFunc)
                                        }

                                        if (this.userBetFee > 0) {
                                            if (this.userWinFee == 0) {
                                                this.showFailureAlert(this.userBetFee, clearAllFunc)
                                            } else {
                                                this.showSuccessAlert(this.userBetFee, this.userWinFee, clearAllFunc)
                                            }
                                        }
        
                                        this.assassin.back(() => {

                                            this.openDoor(() => {
        
                                                this.prgOthersMapping.forEach((p , key) =>{
                                                    if (p.targetRoom != null){
                                                        p.back(() => {
                                                            p.node.destroy()
                                                        })
                                                      
                                                    } 
                                                    
                                                })

                                                
                                            })
        
                                        })
                                    })
                                })
                            })
                            
                        })
                    }


                    this.countdown--

                }
            }
            countdownFunc()

            Http.get(this.token, this.survivalId).then((response) => {
                
                if (response == undefined) {
                    return
                }
                if (response.code != 200) {
                    this.showToast(response.msg)
                    return
                }

                let data = response.data
                this.promptBoxStageLabel.string = data.survivalId + "期"

                this.userId = data.userId 
                this.survivalId = data.survivalId 
                this.status = data.gameRecord.status

                if (this.status == GameStatusWaiting) {
                    this.promptBox.active = true
                    this.countdownNode.active = false
                    this.genCoinNumber(20, 40, 0, this.promptBoxNumber, data.gameRecord.realJoinCount)
                    this.genCoinNumber(20, 40, 0, this.promptBoxStartNumber, data.gameStartMinCount)

                } else if (this.status == GameStatusStart) {
                    this.promptBox.active = false
                    this.countdownNode.active = true
                    let endTime = new Date(data.gameRecord.expectEndTime).getTime()
                    let nowTime = Date.parse(new Date().toString())
                    let countdown = Math.trunc((endTime - nowTime) / 1000)
                    if (this.countdown == -1) {
                        this.countdown = countdown
                        if (countdown > 60) {
                            this.countdown = 60
                        }
                        
                    }


                } else if (this.status == GameStatusKilling || this.status == GameStatusSettle) {
                    if (this.assassinTargetRoomIndex == -1 && data.gameRecord.deadRoom != null) {
                        this.assassinTargetRoomIndex = data.gameRecord.deadRoom - 1 
                        this.lastDeadRoomIndex = this.assassinTargetRoomIndex
                        this.assassin.setTargetRoom(this.rooms[this.assassinTargetRoomIndex])
                    }
                }

                if (this.status == GameStatusSettle && data.userRecord != null) {
                    this.userWinFee = data.userRecord.winFee
                    this.userBetFee = data.userRecord.realBetFee
                }
                
                
                if (!this.enterSign) {
                    this.enterSign = true
                    Http.enter(this.token, this.survivalId).then((response) => {
                        if (response == undefined) {
                            return
                        }
                        if (response.code != 200) {
                            this.showToast(response.msg)
                            return
                        }
                        let dataEnter = response.data
                        this.setAccountBalance(dataEnter.accountBalance)

                    })
                }

                if (this.status == GameStatusKilling || this.status == GameStatusSettle) {
                    return
                }

                for (let room of this.rooms) {
                    room.clearCoin = true
                }

                for (let roomData of data.roomDetailList) {
                    if (roomData.room == "0") {
                        // 等待区
                        for (let user of roomData.userJoinList) {
                            if (this.prgOthersMapping.has(user.userId)) {
                                continue
                            }

                            let prgNode:Node
                            if (user.userId == this.userId) {
                                prgNode = instantiate(this.prgPre)
                                this.prgNode = prgNode
                                this.prgBetAreaNode = prgNode.getChildByName("bet")
                                this.prgBetNumberLabel = this.prgBetAreaNode.getChildByName("number").getComponent(Label)

                            } else {
                                prgNode = instantiate(this.prgOtherPre)
                                let nameLabel:RichText = prgNode.getChildByName("name").getComponent(RichText);
                                nameLabel.string = "<color=#ffffff>" + user.userName +"</color>";
                            }
                            prgNode.setPosition(this.getPrgStartRandomPostion())
                            let prg = new Prg(prgNode)
                            prg.userId = user.userId
                            prg.waiting = true
                            prg.setEnterMainPostion(this.enterMainPostion)
                            prgNode.parent = this.node
                            
                            prgNode.setScale(0, 0)
                            let prgNodeUITransform = prgNode.getComponent(UITransform)
                           
                            if (user.userId == this.userId) {
                                this.prgMyself = prg
                                prgNodeUITransform.priority = 60
                            } else {
                                prgNodeUITransform.priority = 50
                            }
            
                            this.prgOthersMapping.set(user.userId, prg)
                
                            tween(prgNode)
                            .to(1, { scale: v3(1, 1) })
                            .call(() => { 
                            })
                            .start()
                        }
                    }

                    for (let room of this.rooms) {
                        if (roomData.room == room.id + 1) {
                            room.clearCoin = false
                            this.genCoinNumber(21, 42, 3, room.roomCoinNode, roomData.realBetFee)
                            if (room.coinCount != roomData.realBetFee) {
                                room.coinNumberHint()
                            }
                            room.coinCount = roomData.realBetFee

                            for (let userJoin of roomData.userJoinList) {
                                let index = roomData.room - 1
                                if (this.prgOthersMapping.has(userJoin.userId)) {
                                    if (userJoin.userId == this.userId) {
                                        if (this.prgBetNumberLabel != undefined) {
                                            this.prgBetAreaNode.active = true
                                            this.prgBetNumberLabel.string = data.userRecord.realBetFee
                                        }
                                        continue
                                    } 
                                    let prg = this.prgOthersMapping.get(userJoin.userId)
                                    if (prg.waiting != true) {
                                        if (prg.targetRoom != null && prg.targetRoom.id != index) {
                                            prg.node.destroy()
                                            this.prgOthersMapping.delete(userJoin.userId)
                                        } else {
                                            continue
                                        }
                                    } else {
                                        prg.node.destroy()
                                        this.prgOthersMapping.delete(userJoin.userId)
                                    }
                                }

                                let prgNode:Node
                                
                                if (userJoin.userId == this.userId) {
                                    prgNode = instantiate(this.prgPre)
                                    this.prgNode = prgNode
                                    this.prgBetAreaNode = prgNode.getChildByName("bet")
                                    this.prgBetNumberLabel = this.prgBetAreaNode.getChildByName("number").getComponent(Label)
                                    if (data.userRecord != null) {
                                        this.prgBetAreaNode.active = true
                                        this.prgBetNumberLabel.string = data.userRecord.realBetFee
                                    }
    
                                } else {
                                    prgNode = instantiate(this.prgOtherPre)
                                    let nameLabel:RichText = prgNode.getChildByName("name").getComponent(RichText);
                                    nameLabel.string = "<color=#ffffff>" + userJoin.userName +"</color>";
                                }

                                prgNode.setPosition(this.getPrgStartRandomPostion())

                                let prg = new Prg(prgNode)
                                prg.waiting = false
                                prg.userId = userJoin.userId
                                prg.setEnterMainPostion(this.enterMainPostion)
                                prg.setTargetRoom(this.rooms[index])
                                prgNode.parent = this.node
    
                                prgNode.setScale(0, 0)
                                let prgNodeUITransform = prgNode.getComponent(UITransform)
                               
                                if (userJoin.userId == this.userId) {
                                    this.prgMyself = prg
                                    prgNodeUITransform.priority = 60
                                    this.userTargetRoomIndex = index
                                } else {
                                    prgNodeUITransform.priority = 50
                                }
                                

                                this.prgOthersMapping.set(userJoin.userId, prg)
                                
                                // 本地判断是否已移动
                                if (User.moved(data.survivalId, userJoin.userId)) {
                                    prg.target()
                                    tween(prgNode)
                                    .to(1, { scale: v3(1, 1) })
                                    .call(() => { 
                                    })
                                    .start()

                                    continue
                                }
                                
                                User.move(data.survivalId, userJoin.userId)

                                tween(prgNode)
                                .to(1, { scale: v3(1, 1) })
                                .call(() => { 
                                    prg.move()
                                })
                                .start()
                            }
                        }
                    }
                }

                for (let room of this.rooms) {
                    if (room.clearCoin) {
                        this.genCoinNumber(21, 42, 3, room.roomCoinNode, 0)
                    }
                }

            })

          }
          func()
          setInterval(func, 1000)
          
          // 取消计时器
          //clearInterval(intervalId);
    
    }

    showAssassinAlert(func: () => void) {
        //this.alertWindow.setSiblingIndex(this.selectMoneyButton.getSiblingIndex() + 1)
        this.alertWindow.active = true
        this.alertWindowAssassin.active = true
        this.alertWindowSuccess.active = false
        this.alertWindowFailure.active = false
        this.alertWindowBystander.active = false

        tween(this.alertWindowAssassin)
        .then(tween().to(0.3,{scale:v3(1.1, 1.1)}).to(0.5,{scale:v3(1.0, 1.0)})).repeat(5).call(() =>{
            func()
            this.alertWindow.active = false
            this.alertWindowAssassin.active = false
            this.alertWindowSuccess.active = false
            this.alertWindowFailure.active = false
            this.alertWindowBystander.active = false 
        }).start();
    }

    showBystanderAlert(num:number, func: () => void) {
        //this.alertWindow.setSiblingIndex(this.selectMoneyButton.getSiblingIndex() + 1)
        this.alertWindow.active = true
        this.alertWindowAssassin.active = false
        this.alertWindowSuccess.active = false
        this.alertWindowFailure.active = false
        this.alertWindowBystander.active = true
        let bystanderCoin = this.alertWindowBystander.getChildByName("text").getChildByName("coin").getChildByName("number").getComponent(Label)
        let msg = "刺客杀掉「***」里的所有人\n幸存者瓜分里面的水晶"
        let roomName = this.roomNameMapping.get(this.lastDeadRoomIndex)
        this.alertWindowBystanderLabel.string = msg.replace("***", roomName)
        bystanderCoin.string = num + ""
        //this.genCoinNumber(20, 40, 0, bystanderCoin, num)

        setTimeout(() =>{
            func()
            this.alertWindow.active = false
            this.alertWindowAssassin.active = false
            this.alertWindowSuccess.active = false
            this.alertWindowFailure.active = false
            this.alertWindowBystander.active = false 
        }, 8000)
    }

    showSuccessAlert(betNum:number, winNum:number, func: () => void) {
        //this.alertWindow.setSiblingIndex(this.selectMoneyButton.getSiblingIndex() + 1)
        this.alertWindow.active = true
        this.alertWindowAssassin.active = false
        this.alertWindowSuccess.active = true
        this.alertWindowFailure.active = false
        this.alertWindowBystander.active = false

        let leftCoin = this.alertWindowSuccess.getChildByName("left").getChildByName("coin").getChildByName("number").getComponent(Label)
        leftCoin.string = betNum + ""
        //this.genCoinNumber(20, 40, 0, leftCoin, betNum)

        let rightCoin = this.alertWindowSuccess.getChildByName("right").getChildByName("coin").getChildByName("number").getComponent(Label)
        rightCoin.string = winNum.toFixed(3)
        //this.genCoinNumber(20, 40, 0, rightCoin, winNum)

        setTimeout(() =>{
            func()
            this.alertWindow.active = false
            this.alertWindowAssassin.active = false
            this.alertWindowSuccess.active = false
            this.alertWindowFailure.active = false
            this.alertWindowBystander.active = false 
        }, 8000)
    }

    showFailureAlert(betNum:number, func: () => void) {
        //this.alertWindow.setSiblingIndex(this.selectMoneyButton.getSiblingIndex() + 1)
        this.alertWindow.active = true
        this.alertWindowAssassin.active = false
        this.alertWindowSuccess.active = false
        this.alertWindowFailure.active = true
        this.alertWindowBystander.active = false

        let leftCoin = this.alertWindowFailure.getChildByName("left").getChildByName("coin").getChildByName("number").getComponent(Label)
        //this.genCoinNumber(20, 40, 0, leftCoin, betNum)
        leftCoin.string = betNum + ""

        let rightCoin = this.alertWindowFailure.getChildByName("right").getChildByName("coin").getChildByName("number").getComponent(Label)
        //this.genCoinNumber(20, 40, 0, rightCoin, betNum)
        rightCoin.string = betNum + ""

        setTimeout(() =>{
            func()
            this.alertWindow.active = false
            this.alertWindowAssassin.active = false
            this.alertWindowSuccess.active = false
            this.alertWindowFailure.active = false
            this.alertWindowBystander.active = false 
        }, 8000)
    }

    update(deltaTime: number) {
        // let assassinPosition = this.assassinNode.getPosition()
        // console.log(assassinPosition)
        // let range = 1
        // if ((assassinPosition.x >= this.assassin.targetRoom.enterPostion.x - range && assassinPosition.x <= this.assassin.targetRoom.enterPostion.x + range) && 
        // (assassinPosition.y >= this.assassin.targetRoom.enterPostion.y - range && assassinPosition.y <= this.assassin.targetRoom.enterPostion.y + range)) {
        //     this.assassin.pause()
        // }
        
    }



    getPrgStartRandomPostion():Vec3 {
        return v3(this.initAreaStartPostion.x + Util.getRandmNumber(0, this.initAreaWidth), this.initAreaStartPostion.y + Util.getRandmNumber(0, this.initAreaHeight))
    }

    getToken():string {
        let token = localStorage.getItem('u_dc_token') || ''
        if (Config.isLocal()) {
            token = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJjMjlmMWY3MC1kZWJiLTQyNDEtYmJhYi05NDNmNWJhMWMxYzgiLCJpZCI6IjEwMDA3IiwiZXhwIjoxNzAxMjI1Nzk5LCJpYXQiOjE2OTg2MzM3OTk2MDh9.pVFRvpU1jC7NjyieP1sA9KifhV4hbCR1MWhdq0Qy2AqxeS4zFM2UBK6EKPwzYdpui2RZSxzbbOvMAWPOXK7cLRLxQDkAa1-4zzaTvnMN8RM0lx0PWExENx8kz4TxM6katVF61c37UDfYfL0PKJ8EdCh7QZNT9PPSTMEMh5_kNnQ"
        }

        return token
    }


    init() {
        document.title = "大逃杀"
        this.token = this.getToken()

        let backNode = this.node.getChildByName("back")
        backNode.on(Node.EventType.TOUCH_START, function(t) {
            window.history.go(-1); 
        },this)

        let roomsArea = this.node.getChildByName("rooms")
        let roomsAreaUITransform = roomsArea.getComponent(UITransform)
        this.roomsAreaWidth = roomsAreaUITransform.width
        this.roomsAreaHeight = this.roomsAreaWidth * 1.248
        roomsAreaUITransform.height = this.roomsAreaHeight

        this.assassinNode = this.node.getChildByName("assassin")
        let assassinNodeUITransform = this.assassinNode.getComponent(UITransform)
        assassinNodeUITransform.priority = 70
        this.assassinNode.setPosition(v3(this.roomsAreaWidth * 0.6, -this.roomsAreaHeight * 0.33))
        this.assassin = new Assassin(this.assassinNode, v3(this.roomsAreaWidth * 0.185, -this.roomsAreaHeight * 0.33))
       
        this.coinNumberMy = this.genCoinNumberArea(v3(-this.roomsAreaWidth * 0.45, this.roomsAreaHeight * 0.55))
        this.coinNumberMy.scale = v3(1.3, 1.3)
        this.setAccountBalance(0)


        // this.prgNode = this.node.getChildByName("prg");
        // let prgNodeUITransform = this.prgNode.getComponent(UITransform)
        // prgNodeUITransform.priority = 60

        // 提示框
        let alertWindowImageHeight = this.roomsAreaWidth * 414 / 1125
        this.alertWindow = this.node.getChildByName("alertWindow")
        let alertWindowUITransform = this.alertWindow.getComponent(UITransform)
        alertWindowUITransform.priority = 100

        this.alertWindowAssassin = this.alertWindow.getChildByName("assassin")
        this.selectedMask = this.node.getChildByName("selectedMask")
        this.selectedMaskUITransform = this.selectedMask.getComponent(UITransform)


        this.alertWindowSuccess = this.alertWindow.getChildByName("success")
        let alertWindowSuccessUITransform = this.alertWindowSuccess.getComponent(UITransform)
        alertWindowSuccessUITransform.height = alertWindowImageHeight
        this.alertWindowFailure = this.alertWindow.getChildByName("failure")
        let alertWindowFailureUITransform = this.alertWindowFailure.getComponent(UITransform)
        alertWindowFailureUITransform.height = alertWindowImageHeight
        this.alertWindowBystander = this.alertWindow.getChildByName("bystander")
        let alertWindowBystanderUITransform = this.alertWindowBystander.getComponent(UITransform)
        alertWindowBystanderUITransform.height = alertWindowImageHeight
        this.alertWindowBystanderLabel = this.alertWindowBystander.getChildByName("text").getComponent(Label)

        this.enterMainPostion = v3(this.roomsAreaWidth * 0.185, -this.roomsAreaHeight * 0.5)
        let corner1Position = v3(this.enterMainPostion.x, -this.roomsAreaHeight * 0.18)
        let corner2Position = v3(this.enterMainPostion.x, this.roomsAreaHeight * 0.13)

        // 房间顺时针 中间的房价最后一个
        // 房间1
        let room0EnterPosition = v3(this.roomsAreaWidth * 0.03, corner1Position.y)
        let room0CenterPosition = v3(room0EnterPosition.x, -this.roomsAreaHeight * 0.34)
        let room0AreaPrgPosition = v3(-this.roomsAreaWidth * 0.06, -this.roomsAreaHeight * 0.35)
        let room0AreaPrgWidth = this.roomsAreaWidth * 0.25
        let room0AreaPrgHeight = this.roomsAreaHeight * 0.1
        let room0AreaPosition = v3(-this.roomsAreaWidth * 0.06, -this.roomsAreaHeight * 0.354)
        let room0AreaWidth = this.roomsAreaWidth * 0.37
        let room0AreaHeight = this.roomsAreaHeight * 0.178
        let room0 = new Room(0, room0EnterPosition, room0CenterPosition, 
            room0AreaPrgPosition, room0AreaPrgWidth, room0AreaPrgHeight,
            room0AreaPosition, room0AreaWidth, room0AreaHeight)
        room0.addPath(corner1Position)
        this.rooms[0] = room0 

        // 房间2
        let room1EnterPosition = v3(-this.roomsAreaWidth * 0.18, corner1Position.y)
        let room1CenterPosition = v3(-this.roomsAreaWidth * 0.35, corner1Position.y)
        let room1AreaPrgPosition = v3(-this.roomsAreaWidth * 0.37, -this.roomsAreaHeight * 0.28)
        let room1AreaPrgWidth = this.roomsAreaWidth * 0.15
        let room1AreaPrgHeight = this.roomsAreaHeight * 0.22
        let room1AreaPosition = v3(-this.roomsAreaWidth * 0.38, -this.roomsAreaHeight * 0.275)
        let room1AreaWidth = this.roomsAreaWidth * 0.26
        let room1AreaHeight = this.roomsAreaHeight * 0.35
        let room1 = new Room(1, room1EnterPosition, room1CenterPosition, 
            room1AreaPrgPosition, room1AreaPrgWidth, room1AreaPrgHeight,
            room1AreaPosition, room1AreaWidth, room1AreaHeight)
        room1.addPath(corner1Position)
        this.rooms[1] = room1

        // 房间3
        let room2EnterPosition = v3(-this.roomsAreaWidth * 0.18, corner2Position.y)
        let room2CenterPosition = v3(-this.roomsAreaWidth * 0.35, corner2Position.y)
        let room2AreaPrgPosition = v3(-this.roomsAreaWidth * 0.37, this.roomsAreaHeight * 0.06)
        let room2AreaPrgWidth = this.roomsAreaWidth * 0.15
        let room2AreaPrgHeight = this.roomsAreaHeight * 0.23
        let room2AreaPosition = v3(-this.roomsAreaWidth * 0.38, this.roomsAreaHeight * 0.06)
        let room2AreaWidth = this.roomsAreaWidth * 0.26
        let room2AreaHeight = this.roomsAreaHeight * 0.35  
        let room2 = new Room(2, room2EnterPosition, room2CenterPosition, 
            room2AreaPrgPosition, room2AreaPrgWidth, room2AreaPrgHeight,
            room2AreaPosition, room2AreaWidth, room2AreaHeight)
        room2.addPath(corner2Position)
        this.rooms[2] = room2   

        // 房间4
        let room3EnterPosition = v3(-this.roomsAreaWidth * 0.18, corner2Position.y)
        let room3CenterPosition = v3(room3EnterPosition.x, this.roomsAreaHeight * 0.34)
        let room3AreaPrgPosition = v3(-this.roomsAreaWidth * 0.32, this.roomsAreaHeight * 0.35)
        let room3AreaPrgWidth = this.roomsAreaWidth * 0.3
        let room3AreaPrgHeight = this.roomsAreaHeight * 0.15
        let room3AreaPosition = v3(-this.roomsAreaWidth * 0.32, this.roomsAreaHeight * 0.35)
        let room3AreaWidth = this.roomsAreaWidth * 0.4
        let room3AreaHeight = this.roomsAreaHeight * 0.25
        let room3 = new Room(3, room3EnterPosition, room3CenterPosition, 
            room3AreaPrgPosition, room3AreaPrgWidth, room3AreaPrgHeight,
            room3AreaPosition, room3AreaWidth, room3AreaHeight)
        room3.addPath(corner2Position)
        this.rooms[3] = room3
        

        // 房间5
        let room4EnterPosition = v3(-this.roomsAreaWidth * 0.06, corner2Position.y)
        let room4CenterPosition = v3(room4EnterPosition.x, this.roomsAreaHeight * 0.3)
        let room4AreaPrgPosition = v3(this.roomsAreaWidth * 0.001, this.roomsAreaHeight * 0.30)
        let room4AreaPrgWidth = this.roomsAreaWidth * 0.18
        let room4AreaPrgHeight = this.roomsAreaHeight * 0.10
        let room4AreaPosition = v3(this.roomsAreaWidth * 0.001, this.roomsAreaHeight * 0.30)
        let room4AreaWidth = this.roomsAreaWidth * 0.26
        let room4AreaHeight = this.roomsAreaHeight * 0.18
        let room4 = new Room(4, room4EnterPosition, room4CenterPosition, 
            room4AreaPrgPosition, room4AreaPrgWidth, room4AreaPrgHeight,
            room4AreaPosition, room4AreaWidth, room4AreaHeight)
        room4.addPath(corner2Position)
        this.rooms[4] = room4

        // 房间6
        let room5EnterPosition = v3(corner2Position.x, corner2Position.y)
        let room5CenterPosition = v3(corner1Position.x, this.roomsAreaHeight * 0.3)
        let room5AreaPrgPosition = v3(this.roomsAreaWidth * 0.32, this.roomsAreaHeight * 0.33)
        let room5AreaPrgWidth = this.roomsAreaWidth * 0.28
        let room5AreaPrgHeight = this.roomsAreaHeight * 0.16
        let room5AreaPosition = v3(this.roomsAreaWidth * 0.322, this.roomsAreaHeight * 0.332)
        let room5AreaWidth = this.roomsAreaWidth * 0.38
        let room5AreaHeight = this.roomsAreaHeight * 0.28
        let room5 = new Room(5, room5EnterPosition, room5CenterPosition, 
            room5AreaPrgPosition, room5AreaPrgWidth, room5AreaPrgHeight,
            room5AreaPosition, room5AreaWidth, room5AreaHeight)
        //room5.addPath()
        this.rooms[5] = room5

        // 房间7
        let room6EnterPosition = v3(this.enterMainPostion.x, -this.roomsAreaHeight * 0.05)
        let room6CenterPosition = v3(this.roomsAreaWidth * 0.35, room6EnterPosition.y)
        let room6AreaPrgPosition = v3(this.roomsAreaWidth * 0.38, -this.roomsAreaHeight * 0.1)
        let room6AreaPrgWidth = this.roomsAreaWidth * 0.18
        let room6AreaPrgHeight = this.roomsAreaHeight * 0.22
        let room6AreaPosition = v3(this.roomsAreaWidth * 0.382, -this.roomsAreaHeight * 0.095)
        let room6AreaWidth = this.roomsAreaWidth * 0.252
        let room6AreaHeight = this.roomsAreaHeight * 0.32
        let room6 = new Room(6, room6EnterPosition, room6CenterPosition, 
            room6AreaPrgPosition, room6AreaPrgWidth, room6AreaPrgHeight,
            room6AreaPosition, room6AreaWidth, room6AreaHeight)
        //room6.addPath()
        this.rooms[6] = room6



        // 房间8
        let room7EnterPosition = v3(-this.roomsAreaWidth * 0.06, corner1Position.y)
        let room7CenterPosition = v3(room7EnterPosition.x, -this.roomsAreaHeight * 0.01)
        let room7AreaPrgPosition = v3(-this.roomsAreaWidth * 0.07, -this.roomsAreaHeight * 0.02)
        let room7AreaPrgWidth = this.roomsAreaWidth * 0.23
        let room7AreaPrgHeight = this.roomsAreaHeight * 0.08
        let room7AreaPosition = v3(-this.roomsAreaWidth * 0.065, -this.roomsAreaHeight * 0.022)
        let room7AreaWidth = this.roomsAreaWidth * 0.36
        let room7AreaHeight = this.roomsAreaHeight * 0.15
        let room7 = new Room(7, room7EnterPosition, room7CenterPosition, 
            room7AreaPrgPosition, room7AreaPrgWidth, room7AreaPrgHeight,
            room7AreaPosition, room7AreaWidth, room7AreaHeight)
        room7.addPath(corner1Position)
        this.rooms[7] = room7

        this.toastNode = this.node.getChildByName("toast")
        let toastNodeUITransform = this.toastNode.getComponent(UITransform)
        toastNodeUITransform.priority = 90
        this.toastMsgLabel = this.toastNode.getChildByName("msg").getComponent(Label)

        let robot = this.node.getChildByName("robot")
        let robotUITransform = robot.getComponent(UITransform)
        robotUITransform.priority = 80

        this.selectMoneyButton = this.node.getChildByName("selectMoney")
        let selectMoneyButtonUITransform = this.selectMoneyButton.getComponent(UITransform)
        selectMoneyButtonUITransform.priority = 80
        let selectMoneyNumber = this.selectMoneyButton.getChildByName("number")
        let directive = this.selectMoneyButton.getChildByName("directive")
        let selectArea = this.selectMoneyButton.getChildByName("selectArea")

        let area01 = this.selectMoneyButton.getChildByName("area01")
        let area1 = this.selectMoneyButton.getChildByName("area1")
        let area10 = this.selectMoneyButton.getChildByName("area10")
        let area50 = this.selectMoneyButton.getChildByName("area50")

        this.selectMoneyButton.on(Node.EventType.TOUCH_START, function(t) {
            if (this.userTargetRoomIndex == -1) {
                this.showToast("请先选择房间")
                return
            }
            if (this.userAccountBalance < this.userSelectBetFee) {
                this.showToast("水晶数量不足")
                return
            }
            
            if (this.prgMyself.targetRoom == null) {
                User.move(this.survivalId, this.userId)
                this.prgMyself.setTargetRoom(this.rooms[this.userTargetRoomIndex])
                this.prgMyself.move()
            } else {
                this.prgMyself.changeTargetRoom(this.rooms[this.userTargetRoomIndex])
            }
            
            Http.join(this.token, this.userSelectBetFee, this.survivalId, this.userTargetRoomIndex + 1).then((response) => {
                if (response == undefined) {
                    return
                }
                if (response.code != 200) {
                    this.showToast(response.msg)
                    return
                }
                let data = response.data
                this.setAccountBalance(data.accountBalance)
            })
        },this)

        let areaShowFunc = () => {
            if (this.areaShow) {
                area01.active = false
                area1.active = false
                area10.active = false
                area50.active = false
            } else {
                area01.active = true
                area1.active = true
                area10.active = true
                area50.active = true
            }

            this.areaShow = !this.areaShow 
        }

        area01.on(Button.EventType.CLICK, (button: Button) => {
            areaShowFunc()
            this.userSelectBetFee = 0.1
            this.genCoinNumber(20, 40, 0, selectMoneyNumber, this.userSelectBetFee)
        }, this);

        area1.on(Button.EventType.CLICK, (button: Button) => {
            areaShowFunc()
            this.userSelectBetFee = 1
            this.genCoinNumber(20, 40, 0, selectMoneyNumber, this.userSelectBetFee)
        }, this);

        area10.on(Button.EventType.CLICK, (button: Button) => {
            areaShowFunc()
            this.userSelectBetFee = 10
            this.genCoinNumber(20, 40, 0, selectMoneyNumber, this.userSelectBetFee)
        },this)


        area50.on(Button.EventType.CLICK, (button: Button) => {
            areaShowFunc()
            this.userSelectBetFee = 50
            this.genCoinNumber(20, 40, 0, selectMoneyNumber, this.userSelectBetFee)
        },this)

        selectArea.on(Button.EventType.CLICK, (button: Button) => {
            areaShowFunc()
        },this)

        this.genCoinNumber(20, 40, 0, selectMoneyNumber, this.userSelectBetFee)

        this.countdownNode = this.node.getChildByName("countdown")
        this.countdownNumber = this.countdownNode.getChildByName("number")
        this.genCoinNumber(20, 40, 0, this.countdownNumber, 60)

        this.promptBox = this.node.getChildByName("promptBox")
        this.promptBox.setPosition(v3(this.promptBox.getPosition().x, this.roomsAreaHeight/2 + 70))
        this.promptBoxNumber = this.promptBox.getChildByName("number")
        this.promptBoxStartNumber = this.promptBox.getChildByName("startNumber")
        this.promptBoxStageLabel = this.promptBox.getChildByName("stage").getComponent(Label)
        this.genCoinNumber(18, 36, 0, this.promptBoxNumber, 0)
        this.genCoinNumber(18, 36, 0, this.promptBoxStartNumber, 0)


        this.initAreaStartPostion = v3(-this.roomsAreaWidth * 0.45, this.selectMoneyButton.getPosition().y + selectMoneyButtonUITransform.height/2)
        this.initAreaWidth =  this.roomsAreaWidth * 0.9
        this.initAreaHeight = roomsArea.getPosition().y - this.roomsAreaHeight/2 -  (this.selectMoneyButton.getPosition().y + selectMoneyButtonUITransform.height/2)


        room0.roomCoinNode = this.genCoinNumberArea(v3(-this.roomsAreaWidth * 0.19, -this.roomsAreaHeight * 0.305))
        room1.roomCoinNode = this.genCoinNumberArea(v3(-this.roomsAreaWidth * 0.45, -this.roomsAreaHeight * 0.15))
        room2.roomCoinNode = this.genCoinNumberArea(v3(-this.roomsAreaWidth * 0.45, this.roomsAreaHeight * 0.185))
        room3.roomCoinNode = this.genCoinNumberArea(v3(-this.roomsAreaWidth * 0.45, this.roomsAreaHeight * 0.435))
        room4.roomCoinNode = this.genCoinNumberArea(v3(-this.roomsAreaWidth * 0.085, this.roomsAreaHeight * 0.355))
        room5.roomCoinNode = this.genCoinNumberArea(v3(this.roomsAreaWidth * 0.17, this.roomsAreaHeight * 0.43))
        room6.roomCoinNode = this.genCoinNumberArea(v3(this.roomsAreaWidth * 0.285, this.roomsAreaHeight * 0.02))
        room7.roomCoinNode = this.genCoinNumberArea(v3(-this.roomsAreaWidth * 0.19, this.roomsAreaHeight * 0.02))

        let doorMainLeftNode = this.node.getChildByName("doorMainLeft")
        let doorMainLeftNodeUITransform = doorMainLeftNode.getComponent(UITransform)
        doorMainLeftNodeUITransform.width = this.roomsAreaWidth * 0.092
        doorMainLeftNodeUITransform.height = doorMainLeftNodeUITransform.width * 90 / 102
        doorMainLeftNode.setPosition(v3(this.roomsAreaWidth * 0.138, -this.roomsAreaHeight * 0.445))
        doorMainLeftNode.setScale(v3(0, 1))
        
        let doorMainRightNode = this.node.getChildByName("doorMainRight")
        let doorMainRightNodeUITransform = doorMainRightNode.getComponent(UITransform)
        doorMainRightNodeUITransform.width = doorMainLeftNodeUITransform.width
        doorMainRightNodeUITransform.height = doorMainRightNodeUITransform.width * 90 / 102
        doorMainRightNode.setPosition(v3(this.roomsAreaWidth * 0.318, -this.roomsAreaHeight * 0.445))
        doorMainRightNode.setScale(v3(0, 1))


        let door0Node = instantiate(this.doorHorizontalPre)
        door0Node.parent = this.node
        door0Node.name = "door-0"
        let door0NodeUITransform = door0Node.getComponent(UITransform)
        door0NodeUITransform.width = this.roomsAreaWidth * 0.099
        door0NodeUITransform.height = door0NodeUITransform.width * 60 / 106
        door0Node.setPosition(v3(-this.roomsAreaWidth * 0.031, -this.roomsAreaHeight * 0.261))
        room0.doorNode = door0Node
        door0Node.setScale(v3(0, 1))
        
        let door1Node = instantiate(this.doorVerticalPre)
        door1Node.parent = this.node
        door1Node.name = "door-1"
        let door1NodeUITransform = door1Node.getComponent(UITransform)
        door1NodeUITransform.width = this.roomsAreaWidth * 0.05
        door1NodeUITransform.height = door1NodeUITransform.width * 110 / 54
        door1Node.setPosition(v3(-this.roomsAreaWidth * 0.25, -this.roomsAreaHeight * 0.244))
        room1.doorNode = door1Node
        door1Node.setScale(v3(1, 0))

        let door2Node = instantiate(this.doorVerticalPre)
        door2Node.parent = this.node
        door2Node.name = "door-2"
        let door2NodeUITransform = door2Node.getComponent(UITransform)
        door2NodeUITransform.width = this.roomsAreaWidth * 0.05
        door2NodeUITransform.height = door2NodeUITransform.width * 110 / 54
        door2Node.setPosition(v3(-this.roomsAreaWidth * 0.25, this.roomsAreaHeight * 0.11))
        room2.doorNode = door2Node
        door2Node.setScale(v3(1, 0))

        let door3Node = instantiate(this.doorHorizontalPre)
        door3Node.parent = this.node
        door3Node.name = "door-3"
        let door3NodeUITransform = door3Node.getComponent(UITransform)
        door3NodeUITransform.width = this.roomsAreaWidth * 0.092
        door3NodeUITransform.height = door3NodeUITransform.width * 60 / 106
        door3Node.setPosition(v3(-this.roomsAreaWidth * 0.235, this.roomsAreaHeight * 0.229))
        room3.doorNode = door3Node
        door3Node.setScale(v3(0, 1))

        let door4Node = instantiate(this.doorHorizontalPre)
        door4Node.parent = this.node
        door4Node.name = "door-4"
        let door4NodeUITransform = door4Node.getComponent(UITransform)
        door4NodeUITransform.width = this.roomsAreaWidth * 0.092
        door4NodeUITransform.height = door4NodeUITransform.width * 60 / 106
        door4Node.setPosition(v3(-this.roomsAreaWidth * 0.115, this.roomsAreaHeight * 0.203))
        room4.doorNode = door4Node
        door4Node.setScale(v3(0, 1))

        let door5Node = instantiate(this.doorHorizontalPre)
        door5Node.parent = this.node
        door5Node.name = "door-5"
        let door5NodeUITransform = door5Node.getComponent(UITransform)
        door5NodeUITransform.width = this.roomsAreaWidth * 0.092
        door5NodeUITransform.height = door5NodeUITransform.width * 60 / 106
        door5Node.setPosition(v3(this.roomsAreaWidth * 0.145, this.roomsAreaHeight * 0.203))
        room5.doorNode = door5Node
        door5Node.setScale(v3(0, 1))

        let door6Node = instantiate(this.doorVerticalPre)
        door6Node.parent = this.node
        door6Node.name = "door-6"
        let door6NodeUITransform = door6Node.getComponent(UITransform)
        door6NodeUITransform.width = this.roomsAreaWidth * 0.05
        door6NodeUITransform.height = door6NodeUITransform.width * 110 / 54
        door6Node.setPosition(v3(this.roomsAreaWidth * 0.245, -this.roomsAreaHeight * 0.085))
        room6.doorNode = door6Node
        door6Node.setScale(v3(1, 0))

        let door7Node = instantiate(this.doorHorizontalPre)
        door7Node.parent = this.node
        door7Node.name = "door-7"
        let door7NodeUITransform = door7Node.getComponent(UITransform)
        door7NodeUITransform.width = this.roomsAreaWidth * 0.093
        door7NodeUITransform.height = door7NodeUITransform.width * 62 / 106
        door7Node.setPosition(v3(-this.roomsAreaWidth * 0.113, -this.roomsAreaHeight * 0.105))
        room7.doorNode = door7Node
        door7Node.setScale(v3(1, 0))

        let openCloseDuration = 1
        this.openDoor = function (func: () => void) {
            
            tween(doorMainLeftNode)
            .to(openCloseDuration,{scale:v3(0, 1)})
            .call(func)
            .start();

            tween(doorMainRightNode)
            .to(openCloseDuration,{scale:v3(0, 1)})
            .start();

            for (let room of this.rooms) {
                room.open()
            }
        };

        this.closeDoor = function (func: () => void) {
            tween(doorMainLeftNode)
            .to(openCloseDuration,{scale:v3(1, 1)})
            .call(func)
            .start();

            tween(doorMainRightNode)
            .to(openCloseDuration,{scale:v3(1, 1)})
            .start();

            for (let room of this.rooms) {
                room.close()
            }
        };

        this.tipNode = robot.getChildByName("tip")
        let tipMsgLabel = this.tipNode.getChildByName("msg").getComponent(Label)
        
        let tipMsg = ["成功躲避刺客即可获得水晶奖励","上期杀手去了「***」","快选个房间躲起来，刺客要来了"]
    
        setInterval(() => { 
            let index = Math.floor(this.tipMsgIndex % 3)
            
            if (index == 1) {
                if (this.lastDeadRoomIndex != -1) {
                    console.log(this.lastDeadRoomIndex)
                    let roomName = this.roomNameMapping.get(this.lastDeadRoomIndex)
                    tipMsgLabel.string = tipMsg[index].replace("***", roomName)
                }
                
            } else {
                tipMsgLabel.string = tipMsg[index]
            }
            
            this.tipMsgIndex++
        }, 3000);
    }


    showToast(msg:string) {
        this.toastNode.active = true
        this.toastMsgLabel.string = msg

        setTimeout(() =>{
            this.toastNode.active = false
        }, 1000)

    }

    setAccountBalance(accountBalance:number) {
        this.userAccountBalance = Number(accountBalance.toFixed(3))
        this.genCoinNumber(21, 42, 3,this.coinNumberMy, this.userAccountBalance)
    }


    genCoinNumberArea(pos:Vec3):Node {
        let coinNumberNode = instantiate(this.coinNumberPre)
        let coinNumberUITransform = coinNumberNode.getComponent(UITransform)
        coinNumberUITransform.priority = 80
        coinNumberNode.parent = this.node
        coinNumberNode.setPosition(pos)
        this.genCoinNumber(21, 42, 3,coinNumberNode, 0)
        return coinNumberNode
    }

    genCoinNumber(w:number, h:number, spacing:number, parent:Node, num:number) {

        parent.removeAllChildren()

        let numbers = (num+"").split("") 
        
        let i = 0
        let j = 0
        let spacingleft = 5
        let x = spacingleft
        for (let num of numbers) {
            let n = new Node()
            let sp = n.addComponent(Sprite)
            let w1 = w
            let spacing1 = spacing
            if (num == ".") {
                w1 = 15
                spacing1 = 0
                sp.spriteFrame = this.numbersSprite.getSpriteFrame("dot")
                j++
            } else {
                if (j == 1) {
                    w1 = 15 
                }
                j--
                sp.spriteFrame = this.numbersSprite.getSpriteFrame( num + "n")
            }
            
            n.parent = parent
            
            x = x + w1 - spacing1
            n.setPosition(v3(x, 0))
            let t = n.getComponent(UITransform)
            t.width = w
            t.height= h
            i++
        }
    }
}

